<script setup lang="ts">
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';
import { reactive } from 'vue';

const form = reactive({
  username: '',
  password: ''
});

const errorMessage = ref('');
const router = useRouter();

const login = async () => {
  if (form.username === '') {
    errorMessage.value = '用户名不能为空';
    return;
  }
  if (form.password === '') {
    errorMessage.value = '密码不能为空';
    return;
  }
  try {
    const response = await axios.post('/login', {
      username: form.username,
      password: form.password
    });

    if (response.data.token) {
      // 登录成功，存储Token
      localStorage.setItem('token', response.data.token);
      await router.push({name: 'greenHouseInformation'});
    } else {
      errorMessage.value = response.data.message || '登录失败';
    }
  } catch (error) {
    if (error instanceof Error) {
      errorMessage.value = '用户名或密码错误' ;
    } else {
      errorMessage.value = '登录失败：未知错误';
    }
  }
};
</script>

<template>
  <div class="h-full w-full bg-sky-9 flex items-center justify-center">
    <div class="w-30em  bg-white rounded p-16 shadow-2xl">
      <div class="text-center text-2xl font-bold">登录</div>
      <div class="pt-8">
        <ElForm :model="form">
          <ElFormItem>
            <ElInput v-model="form.username" placeholder="请输入用户名" />
          </ElFormItem>
          <ElFormItem>
            <ElInput type="password" v-model="form.password" placeholder="请输入密码" />
          </ElFormItem>
          <ElFormItem v-if="errorMessage">
            <div class="text-red-500">{{errorMessage}}</div>
          </ElFormItem>
          <ElFormItem>
            <ElButton type="primary" @click="login" class="w-full">立即登录</ElButton>
          </ElFormItem>
          <div class="text-3.2 flex justify-around items-center">
            <span class="mr--20">默认用户名：admin</span>
            <span class="mr-10">默认密码：admin</span>
          </div>
        </ElForm>
      </div>
    </div>
  </div>
</template>

<style scoped>

</style>